package com.dotflat.cc.controller;

import com.dotflat.cc.po.ChildrenImportPO;
import com.dotflat.cc.po.ChildrenPO;
import com.dotflat.util.excelUtil.ExcelUtil;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.commons.model.ErrorCode;
import com.matt.commons.model.StatusResponse;
import com.matt.domain.Children;
import com.matt.service.ChildrenService;
import com.matt.service.Photo.PhotoAlbumService;
import com.matt.service.remoteCall.SsoCallService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.transaction.Transactional;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

import static com.matt.foundation.constant.RequestConstant.TICKET;

@RestController
@RequestMapping("/v2/child")
@Slf4j
@Api(tags = "宝宝")
public class RChildController
{

    @Autowired
    private SsoCallService ssoCallService;

    @Autowired
    private ChildrenService childrenService;

    @Autowired
    private PhotoAlbumService albumService;

    @ApiOperation(value = "添加一个宝宝")
    @PostMapping("/add")
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK", response = Children.class),
    })
    @Transactional(rollbackOn = RuntimeException.class)
    public StatusResponse addChild(@RequestHeader(TICKET) String ticket, String childrenId, ChildrenPO children){

        if(children.getLinkMans() == null || children.getLinkMans().size() == 0){
            return StatusResponse.error(ErrorCode.DATE_FORMAT_ERROR, "添加宝宝时联系人不能为空");
        }

        StaffDTO staff = ssoCallService.getStaffDTO(ticket);

        if (StringUtils.isNotBlank(childrenId)){
            //修改逻辑
            Children c = childrenService.update(staff, childrenId, children);
            return StatusResponse.success(c);
        }

        Children c = childrenService.addWithRealtion(ticket, staff, children);

        //给宝宝创建相册
        albumService.getByChildrenId(c.getAreaId(), c.getId(),1);

        return StatusResponse.success(c);
    }

    @ApiOperation(value = "添加一个宝宝")
    @PostMapping("/addByLeads")
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK", response = Children.class),
    })
    @Transactional(rollbackOn = RuntimeException.class)
    public StatusResponse addByLeads(@RequestHeader(TICKET) String ticket, ChildrenPO children){

        if(children.getLinkMans() == null || children.getLinkMans().size() == 0){
            return StatusResponse.error(ErrorCode.DATE_FORMAT_ERROR, "添加宝宝时联系人不能为空");
        }

        StaffDTO staff = ssoCallService.getStaffDTO(ticket);

        Children c = childrenService.addByLeads(ticket, staff, children);

        //给宝宝创建相册
        albumService.getByChildrenId(c.getAreaId(), c.getId(),1);

        return StatusResponse.success(c);
    }

    @ApiOperation(value = "添加一个宝宝")
    @PostMapping(value = "/addByLeadByCrm", produces = "application/json;charset=utf-8") // 新增produces
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK", response = Children.class),
    })
    @Transactional(rollbackOn = RuntimeException.class)
    public StatusResponse addByLeadByCrm(@RequestHeader(TICKET) String ticket,@RequestBody ChildrenPO children){

        if(children.getLinkMans() == null || children.getLinkMans().size() == 0){
            return StatusResponse.error(ErrorCode.DATE_FORMAT_ERROR, "添加宝宝时联系人不能为空");
        }

        StaffDTO staff = ssoCallService.getStaffDTO(ticket);

        Children c = childrenService.addByLeads(ticket, staff, children);

        //给宝宝创建相册
        albumService.getByChildrenId(c.getAreaId(), c.getId(),1);

        return StatusResponse.success(c);
    }

//    @ApiOperation(value = "编辑一个宝宝")
//    @PostMapping("/update")
//    @ApiResponses({
//            @ApiResponse(code = 200,message = "OK", response = Children.class),
//    })
//    @Transactional(rollbackOn = RuntimeException.class)
//    public StatusResponse updateChild(@RequestHeader(TICKET) String ticket, String childrenId, ChildrenPO children){
//
//        StaffDTO staff = ssoCallService.getStaffDTO(ticket);
//
//        Children c = childrenService.update(staff, staff.getId(), children);
//
//
//        return StatusResponse.success(c);
//    }



    /**
     * 下载宝宝导入模板
     *
     * @return 文件下载响应
     */
    @GetMapping(value = "/ChildrenMemorandumPageImportTemplate")
    public ResponseEntity<Resource> ChildrenMemorandumPageImportTemplate() throws UnsupportedEncodingException {
        // 模板文件的URL
        String url = "https://jinzhiweiye.oss-cn-hangzhou.aliyuncs.com/2025/03/01/fc58639855464a7db5de2d8faf151a94boby.xlsx";

        // 下载文件
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Resource> response = restTemplate.getForEntity(url, Resource.class);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        String fileName = URLEncoder.encode("宝宝导入模板.xlsx", String.valueOf(StandardCharsets.UTF_8)); // 对文件名进行 URL 编码
        headers.setContentDispositionFormData("attachment", fileName); // 触发下载
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); // 二进制文件类型

        return ResponseEntity.ok()
                .headers(headers)
                .body(response.getBody());
    }



    @ApiOperation(value = "导入多个宝宝")
    @PostMapping("/importChild")
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK", response = Children.class),
    })
    @Transactional(rollbackOn = RuntimeException.class)
    public StatusResponse importChild(@RequestHeader(TICKET) String ticket,
                                   @RequestParam MultipartFile file) throws Exception{
        StaffDTO staff = ssoCallService.getStaffDTO(ticket);
        ExcelUtil<ChildrenImportPO> util = new ExcelUtil<ChildrenImportPO>(ChildrenImportPO.class);
        List<ChildrenImportPO> importExcel = util.importExcel(file.getInputStream());
        String message = childrenService.importChildrenList(ticket,staff,importExcel);
        return StatusResponse.success(message);
    }
}
